package uqbar.aspectj.observable.perthis;

import uqbar.aspectj.utils.Utils;

/**
 * A simple observable aspect that logs an event in the sysout
 * everytime a field is written with a different value than the current one.  
 * 
 * @author uqbar
 */
public aspect SysoutPerthisObservableAspect pertarget (set(* examples.perthis..*)) {
	public int counter = 0;

	pointcut fieldWrite(Object target, Object newValue) : 
		set(* examples.perthis..*) && args(newValue) && target(target);
	
	void around(Object target, Object newValue) : fieldWrite(target, newValue) {
		String fieldName = thisJoinPoint.getSignature().getName();
		Object oldValue = Utils.getField(target, fieldName);
		
		proceed(target, newValue);
		
		// comparar por null y por equals ?
		if (oldValue != newValue) {
			this.notifyFieldChanged(thisJoinPoint.getThis(), fieldName, oldValue, newValue);
		}
    }
	
	
	protected void notifyFieldChanged(Object target, String fieldName, Object oldValue, Object newValue) {
		this.counter++;
		System.out.println("Updated field :" + target + ":" + fieldName + "(" + oldValue + " -> " + newValue + ")");
	}

}